"use strict";
window.top === window.self;
//var _console = window.console;
//window.console = _console || {};
//window.console.info = _console.info || function() {};
//window.console.debug = _console.debug || function() {};
//window.console.log = _console.log || function() {};
window._console = window.console; //将原始console对象缓存  
window.console = (function(orgConsole) {
  return { //构造的新console对象  
    log: getConsoleFn("log"),
    debug: getConsoleFn("debug"),
    info: getConsoleFn("info"),
    warn: getConsoleFn("warn"),
    exception: getConsoleFn("exception"),
    assert: getConsoleFn("assert"),
    dir: getConsoleFn("dir"),
    dirxml: getConsoleFn("dirxml"),
    trace: getConsoleFn("trace"),
    group: getConsoleFn("group"),
    groupCollapsed: getConsoleFn("groupCollapsed"),
    groupEnd: getConsoleFn("groupEnd"),
    profile: getConsoleFn("profile"),
    profileEnd: getConsoleFn("profileEnd"),
    count: getConsoleFn("count"),
    clear: getConsoleFn("clear"),
    time: getConsoleFn("time"),
    timeEnd: getConsoleFn("timeEnd"),
    timeStamp: getConsoleFn("timeStamp"),
    table: getConsoleFn("table"),
    error: getConsoleFn("error"),
    memory: getConsoleFn("memory"),
    markTimeline: getConsoleFn("markTimeline"),
    timeline: getConsoleFn("timeline"),
    timelineEnd: getConsoleFn("timelineEnd")
  };

  function getConsoleFn(name) {
    return function actionConsole() {
      if (typeof(orgConsole) !== "object") return;
      if (typeof(orgConsole[name]) !== "function") return; //判断原始console对象中是否含有此方法，若没有则直接返回  
      return orgConsole[name].apply(orgConsole, Array.prototype.slice.call(arguments)); //调用原始函数  
    };
  }
}(window._console));
var JSTOOL = function() {
  /*
   * 美化所有checkbox与radio
   * 
   * $('input').iCheck('check'); — 将输入框的状态设置为checked
   * $('input').iCheck('uncheck'); — 移除 checked 状态
   * $('input').iCheck('toggle'); — toggle checked state
   * $('input').iCheck('disable'); — 将输入框的状态设置为 disabled
   * $('input').iCheck('enable'); — 移除 disabled 状态
   * $('input').iCheck('update'); — apply input changes, which were done
   * outside the plugin $('input').iCheck('destroy'); — 移除iCheck样式
   */
  this.changeCheck = function($dom) {
    $dom.iCheck({
      checkboxClass: 'icheckbox_flat-blue',
      radioClass: 'iradio_flat-blue'
    });
  };
  /*
   * 可以参考http://www.cnblogs.com/wuhuacong/p/4761637.html 美化select
   */
  this.changeSelect = function($dom, hasSearch) {
    var selectNum = 0;
    if (typeof(hasSearch) != 'undefined') {
      if (hasSearch == false) {
        selectNum = -1;
      }
    }
    $dom.select2({
      tags: true,
      maximumSelectionLength: 3,
      minimumResultsForSearch: selectNum
        // 最多能够选择的个数
    });
  };
  /*
   * 分页插件
   */
  this.initPageDiv = function($dom, now, all, each, $dom2, change) {
    if (parseInt(now) > parseInt(all)) {
      return;
    }
    var options = {
      currentPage: now, // 当前页
      totalPages: all, // 共几页
      numberOfPages: each, // 每次显示几页
      itemTexts: function(type, page, current) { // 修改显示文字
        switch (type) {
          case "first":
            return "第一页";
          case "prev":
            return "上一页";
          case "next":
            return "下一页";
          case "last":
            return "最后一页";
          case "page":
            return page;
        }
      },
      onPageClicked: function(event, originalEvent, type, page) { // 异步换页
        $dom2.val(page);
        change();
      }
    }
    $dom.bootstrapPaginator(options);
  };
  /*
   * switch 选项插件
   * 
   */
  this.changeToSwitch = function($dom, left, right, onText, offText) {
    $dom.bootstrapSwitch({
      onText: onText,
      offText: offText,
      onColor: "success",
      offColor: "info",
      size: "small",
      onSwitchChange: function(event, state) {
        if (state == true) {
          left();
        } else {
          right();
        }
      }
    });
  };
  /* 日期框 */
  this.datePicker = function($dom, dataformat) {
    var _format = dataformat || "yyyymmdd"
    $dom.datetimepicker({
      format: _format, // "dd MM yyyy - HH:ii P",
      showMeridian: true,
      autoclose: true,
      todayBtn: true,
      minView: 2,
      language: 'zh-CN'
    });
  };
  /* 弹窗 */
  this.alert = function(title, content, callback, className) {
    var confirm = callback && typeof callback === "function" ? callback :
      function() {};
    if (myBrowser() == "IE8") {
      window.top.bootbox.alert({
        buttons: {
          ok: {
            label: '确定',
            className: 'btn-primary'
          }
        },
        message: content,
        callback: function() {
          confirm();
        },
        title: title,
      });
    } else {
      var alertClass = "";
      if (typeof className == "undefined") {
        alertClass = 'offset4 col-md-4 col-md-offset-4';
      } else {
        alertClass = className;
      }
      window.top.$.alert({
        title: title,
        content: content,
        confirm: confirm,
        confirmButton: '确定',
        backgroundDismiss: false,
        confirmButtonClass: 'btn-primary',
        animation: 'zoom',
        closeAnimation: 'scale',
        columnClass: alertClass
      });
    }
  };
  this.confirm = function(title, content, okCallback, cancelCallback, initCallback) {
    var confirm = okCallback && typeof okCallback === "function" ? okCallback : function() {};
    var cancel = cancelCallback && typeof cancelCallback === "function" ? cancelCallback : function() {};
    var afterInit = initCallback && typeof initCallback == "function" ? initCallback : function() {};
    if (myBrowser() == "IE8") {
      var dialog = window.top.bootbox.confirm({
        buttons: {
          confirm: {
            label: '确认',
            className: 'btn-primary'
          },
          cancel: {
            label: '取消',
            className: 'btn-danger'
          }
        },
        message: content,
        callback: function(result) {
          if (result) {
            confirm(dialog.find(".bootbox-body"));
          } else {
            cancel();
          }
        },
        title: title,
      });
      dialog.init(function() {
        afterInit(dialog.find(".bootbox-body"));
      });
    } else {
      var confirm = okCallback && typeof okCallback === "function" ? okCallback :
        function() {};
      var cancel = cancelCallback && typeof cancelCallback === "function" ? cancelCallback :
        function() {};
      window.top.$.confirm({
        title: title,
        content: content,
        confirm: confirm,
        cancel: cancel,
        confirmButton: '确定',
        cancelButton: '取消',
        confirmButtonClass: 'btn-primary',
        cancelButtonClass: 'btn-danger',
        backgroundDismiss: false,
        animation: 'zoom',
        closeAnimation: 'scale',
        onOpen: function() { afterInit(this.$content); }
      });
    }
  };

  this.confirms = function(title, content, okCallback, cancelCallback, initCallback) {
    var confirm = okCallback && typeof okCallback === "function" ? okCallback : function() {};
    var cancel = cancelCallback && typeof cancelCallback === "function" ? cancelCallback : function() {};
    var afterInit = initCallback && typeof initCallback == "function" ? initCallback : function() {};
    if (myBrowser() == "IE8") {
      var dialog = window.bootbox.confirm({
        buttons: {
          confirm: {
            label: '确认1',
            className: 'btn-primary'
          },
          cancel: {
            label: '取消2',
            className: 'btn-danger'
          }
        },
        message: content,
        callback: function(result) {
          if (result) {
            confirm(dialog.find(".bootbox-body"));
          } else {
            cancel();
          }
        },
        title: title,
      });
      dialog.init(function() {
        afterInit(dialog.find(".bootbox-body"));
      });
    } else {
      var confirm = okCallback && typeof okCallback === "function" ? okCallback :
        function() {};
      var cancel = cancelCallback && typeof cancelCallback === "function" ? cancelCallback :
        function() {};
      $.confirm({
        title: title,
        content: content,
        confirm: confirm,
        cancel: cancel,
        confirmButton: '确定',
        cancelButton: '取消',
        confirmButtonClass: 'btn-yes',
        cancelButtonClass: 'btn-no',
        backgroundDismiss: false,
        animation: 'zoom',
        closeAnimation: 'scale',
        onOpen: function() { afterInit(this.$content); }
      });

    }
  };




  this.dialog = function(title, content) {
    window.top.$.dialog({
      title: title,
      content: content,
      animation: 'zoom',
      closeAnimation: 'scale'
    });
  };
  // 处理空防止报错
  this.null2empty = function(str) {
    if (str == null) {
      return "";
    }
    return str;
  };
  // 刷新当前页面
  this.replacelocalhost = function(url) {
    var base = document.getElementsByTagName("base")[0];
    if (base) {
      window.location.replace(base.getAttribute("href") + url);
    } else {
      window.location.replace(url);
    }
  };
  // 获取跳页时父页面传来的参数
  this.getParam = function(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) {
      return unescape(r[2]);
    } else {
      return null;
    }
  }

  // 获取域名
  this.getUrlArea = function() {
    var r = window.location.host;
    return r;
  }

  //获取当前调用协议
  this.getProtocol = function() {
    var p = window.location.protocol + "//";
    return p;
  }
  this.urlHead = function() {
    return this.getProtocol() + this.getUrlArea();
  }

  this.urlhead = this.urlHead;

  // 防参数乱码 index为参数在url参数列表的顺序号
  this.getDecodeUrl = function(index) {
    var url = decodeURI(location.href);
    var result = url.split("?")[1].split("&")[index].split("=")[1];
    return result;
  }

  // 处理缓存中json字符串的方法
  this.changeJsonToObj = function(json) {
    var goods = json.split("#");
    var obj = new Array();
    if (json != "") {
      for (var i = 0; i < goods.length; i++) {
        obj.push(JSON.parse(goods[i]));
      }
    }
    return obj;
  }

  /**
   * 替换某个字符串为另外一个字符串函数
   * 
   * @param {any} bigStr  全部字符
   * @param {any} str1 被替换的字符
   * @param {any} str2 新字符
   * @returns 新的字符串
   */
  this.replaceAll = function(bigStr, str1, str2) { //把bigStr中的所有str1替换为str2
    var reg = new RegExp(str1, 'gm');
    return bigStr.replace(reg, str2);
  }

  this.deleteGoodsFromCart = function(ids, ifToBalance) {
    var r = "";
    var goodis = localStorage.getItem("cartGoodsJsonInStorage").split("#");
    var goodsInStorage = new Array();
    if (localStorage.getItem("cartGoodsJsonInStorage") != "") {
      for (var i = 0; i < goodis.length; i++) {
        goodsInStorage.push(JSON.parse(goodis[i]));
      }
    }
    //    var goodsInStorage = tool.changeJsonToObj(localStorage
    //      .getItem("cartGoodsJsonInStorage"));
    var temp = []; // 临时数组1
    var goodsInStorageResult = []; // 临时数组2
    var idss = ids.split(",")
    if (idss.length != 0) {
      for (var i = 0; i < idss.length; i++) {
        temp[idss[i]] = true;
        // 删除 用于判断商品是否在购物车中的变量
        localStorage.removeItem(idss[i]);
        // 改变购物车标签商品数量角标
        var n = localStorage.getItem("numOfCartGoodsInStorage");
        localStorage.setItem("numOfCartGoodsInStorage", n - 1);
      }
      // 删除缓存中json字符串中被选中的商品信息
      if (goodsInStorage.length != 0) {
        for (var j = 0; j < goodsInStorage.length; j++) {
          if (!temp[goodsInStorage[j].ID]) {
            goodsInStorageResult.push(goodsInStorage[j]);
          }
        }
      }
      // 将删除后的对象转为json存入缓存及数据库
      var cartGoodsJsonInStorage = "";
      if (goodsInStorageResult.length != 0) {
        cartGoodsJsonInStorage = JSON
          .stringify(goodsInStorageResult[0]);
        for (var n = 1; n < goodsInStorageResult.length; n++) {
          cartGoodsJsonInStorage += "#" +
            JSON.stringify(goodsInStorageResult[n]);
        }
        localStorage.setItem("cartGoodsJsonInStorage",
          cartGoodsJsonInStorage);
      }
      $.ajax({
        url: window.location.protocol + "//" + window.location.host +
          "/csfwpt_console/restful/shopping/chart",
        data: {
          goodsInfo: cartGoodsJsonInStorage
        },
        dataType: "TEXT",
        type: "POST"
      }).done(function(data) {
        if (ifToBalance == 0 || ifToBalance == "0") {
          if (data == "SUCCESS") {
            createPage();
          } else if (data == "FAIL") {
            $("#loadingToast").hide();
            $("#info").text("删除失败，请联系管理员");
            $("#dialog1").fadeIn(200);
          }
        } else {
          if (data == "SUCCESS") {
            console.info("pay")
              // 模拟支付成功
            var url = "pay_success.html";
            window.location.href = encodeURI(url);
          } else if (data == "FAIL") {
            console.info("fail");
          }
        }
      });
    }
    return r;
  }

  this.changePageUrl = function(title, url) {
    // 改变当前页url
    function pushHistory() {
      var state = {
        title: title,
        url: url
      };
      window.history.replaceState(state, title, url);
    }
    // 支付后续操作如果后退直接后退到输入税号页
    var bool = false;
    setTimeout(function() {
      bool = true;
    }, 100);
    pushHistory();
    window.addEventListener("popstate", function(e) {
      if (bool) {
        window.history.go(-1);
      } else {
        pushHistory();
      }
    }, false);
  }

  this.changeParentPageUrl = function(title, url) {
    // 改变当前页url
    function pushHistory() {
      var state = {
        title: title,
        url: url
      };
      window.parent.history.replaceState(state, title, url);
    }
    // 支付后续操作如果后退直接后退到输入税号页
    var bool = false;
    setTimeout(function() {
      bool = true;
    }, 100);
    pushHistory();
    window.addEventListener("popstate", function(e) {
      if (bool) {
        window.history.go(-1);
      } else {
        pushHistory();
      }
    }, false);
  }

  this.showModal = function() {
    // var html = '<div class="modal fade" id="modal1">'+
    // ' <div class="modal-dialog ">'+
    // '<div class="modal-content">'+
    // ' <div class="modal-header">'+
    // ' <button type="button" class="close" data-dismiss="modal"
    // aria-hidden="false">×</button>'+
    // '<h4 class="modal-title">模板详情</h4>'+
    // '</div>'+
    // '<div class="modal-body">'+
    // '<form>'+
    // ' <div class="form-group"> '+
    // ' <label class="control-label">模板名称：</label> '+
    // ' <span id="moTitle"></span>'+
    // ' </div> '+
    // ' <div class="form-group"> '+
    // ' <label class="control-label">模板CODE：</label> '+
    // ' <span id="moCode"></span>'+
    // ' </div> '+
    // ' <div class="form-group"> '+
    // ' <label class="control-label">模板内容：</label> '+
    // ' <span id="moContent"></span>'+
    // ' </div> '+
    // ' </form>'+
    // ' </div>'+
    // ' <div class="modal-footer">'+
    // ' <a class="btn btn-default" data-dismiss="modal">关闭</a>'+
    // ' </div>'+
    // '</div>'+
    // '</div>'+
    // '</div>';
    // alert(html)
    // $("#workspace").append(html);
    $("#modal1").modal("show");
  }

  // 打开模态框
  var fatherBody = $(window.top.document.body);
  this.openModal = function(validate, saveInfo, watermark, floor, callback) {
      var id = 'moda';
      var dialog = $('#' + id);
      if (dialog.length == 0) {
        dialog = $('<div class="modal fade" role="dialog" id="' + id +
          '"/>');
        dialog.appendTo(fatherBody);
      }
      dialog.load("tool/toImageUpload?validate=" + validate + "&saveInfo=" +
        saveInfo + "&watermark=" + encodeURI(encodeURI(watermark)) +
        "&floor=" + floor + "&callback=" + callback,
        function() {
          dialog.modal({
            backdrop: false
          });
        });
      $('#pdfDownload_button').attr('data-dismiss', '');
      // fatherBody
      // .append("<div id='backdropId' class='modal-backdrop fade
      // in'></div>");
    }
    // 关闭模态框
    //	this.closeModal = function() {
    //		var fatherBody = $(window.top.document.body);
    //		console.info(fatherBody.find("#moda"))
    //		fatherBody.find("#moda").on('hidden.bs.modal', function(e) {
    //			//fatherBody.find("#backdropId").removeData("bs.modal");
    //			 $(this).removeData("bs.modal");
    //		});
    //	}

  //上传图片
  this.getUploadResult = function(input, validate, saveInfo, floor, watermark) {
    if (this.value == "") {
      return;
    }
    uploadImage(validate, saveInfo, watermark, "",
      function(data) {
        uploadResult = data;
        if (floor == "0") {
          window.parent[0].showImage(uploadResult);
        } else if (floor == "1") {
          window.parent.showImage(uploadResult);
        } else if (floor == "2") {
          showImage(uploadResult);
        }
      });
  }

  //上传文件
  this.getFileUploadResult = function(compress) {
    // alert("file上传");
    if (this.value == "") {
      return;
    }
    var flag = false;
    //true为不压缩，false为压缩
    /*if(compress == 'adFile'){
    	flag = false;
    }*/
    uploadResource(flag, "tool/blank",
      function(data) {
        uploadResult = data;
        window.parent[0].showFile(uploadResult);
      });
  }

  this.ensure = function() {
    if (window.parent[0].showImage) {
      console.log(window.parent);
      window.parent[0].showImage(uploadResult);
    } else {
      console.log(window.parent);
    }
  }

  //点击默认返回按钮关闭浏览器
  this.closeWindow = function() {
    var bool = false;
    setTimeout(function() {
      bool = true;
    }, 100);
    pushHistory();
    window.addEventListener("popstate", function(e) {
      if (bool) {
        //				alert("我监听到了浏览器的返回按钮事件啦");//根据自己的需求实现自己的功能 
        //				WeixinJSBridge.call('closeWindow');
        window.parent.location.href = window.location.protocol + "//" + window.location.host + "/wechatcs/";
      } else {
        pushHistory();
      }
    }, false);
  }

  /**
   * 根据useragent判断设备的方法
   */
  this.getUserAgent = function() {
    var ua = navigator.userAgent;
    if (ua) {
      if (ua.indexOf("Windows NT") != -1) {
        return "Windows";
      } else if (ua.indexOf("Macintosh") != -1) {
        return "iMac";
      } else if (ua.indexOf("iPad") != -1) {
        return "iPad";
      } else if (ua.indexOf("iPhone") != -1) {
        return "iPhone";
      } else if (ua.indexOf("Android") != -1) {
        return "Android";
      } else {
        return "other";
      }
    }
  }
};

var tool = new JSTOOL();
var uploadResult = null;

function pushHistory() {
  var state = {
    title: "title",
    url: "#"
  };
  window.history.pushState(state, "title", "");
}

// 复制到剪切板
function paste() {
  if (window.clipboardData) {
    window.clipboardData.clearData();
    clipboardData.setData("Text", $.trim($("#sqFrame").val()));
    tool.alert("提示", "复制成功！");
  } else {
    tool.alert("提示", "复制失败！请手动复制");
  }
};
// 判断浏览器版本
function myBrowser() {
  var userAgent = navigator.userAgent; // 取得浏览器的userAgent字符串
  var isOpera = userAgent.indexOf("Opera") > -1; // 判断是否Opera浏览器
  var isIE = userAgent.indexOf("compatible") > -1 &&
    userAgent.indexOf("MSIE") > -1 && !isOpera; // 判断是否IE浏览器
  var isFF = userAgent.indexOf("Firefox") > -1; // 判断是否Firefox浏览器
  var isSafari = userAgent.indexOf("Safari") > -1; // 判断是否Safari浏览器
  if (isIE) {
    var IE5 = IE55 = IE6 = IE7 = IE8 = false;
    var reIE = new RegExp("MSIE (\\d+\\.\\d+);");
    reIE.test(userAgent);
    var fIEVersion = parseFloat(RegExp["$1"]);
    IE55 = fIEVersion == 5.5;
    IE6 = fIEVersion == 6.0;
    IE7 = fIEVersion == 7.0;
    IE8 = fIEVersion == 8.0;
    if (IE55) {
      return "IE55";
    }
    if (IE6) {
      return "IE6";
    }
    if (IE7) {
      return "IE7";
    }
    if (IE8) {
      return "IE8";
    }
  } // isIE end
  if (isFF) {
    return "FF";
  }
  if (isOpera) {
    return "Opera";
  }
};

// 查询钥匙盘信息
function getKeyno() {
  var keyInfo = window.top['_CACHE'].searchKeyInfo();
  if (!keyInfo.success) {
    console.info("查询钥匙盘信息失败，失败原因：" + keyInfo.message);
  } else {
    // 获取kpzdbs，开票终端表示
    var key = keyInfo.bean.keyno;
    // var key = "33123456789";
    if (key != null && key != "" && key != "null") {
      return key.substring(2, key.length);
    }
  }
}


/**
 * 分隔获取各个参数
 * 根据URL地址获取其参数
 */
function UrlSearch() {
  var name, value;
  var str = location.href; //取得整个地址栏
  var num = str.indexOf("?");
  str = str.substr(num + 1);
  var arr = str.split("&"); //各个参数放到数组里
  for (var i = 0; i < arr.length; i++) {
    num = arr[i].indexOf("=");
    if (num > 0) {
      name = arr[i].substring(0, num);
      value = arr[i].substr(num + 1);
      this[name] = value;
    }
  }
}